package web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.RandomStringUtils;

import web.servlet.dto.DtoFactory;
import data.model.User;

public class LoginServlet extends AbstractJsonCapableServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final String email = request.getParameter("email");
        final String password = request.getParameter("password");

        final User user = dataLayer.findUserByEmail(email);
        if (user == null || user.getConfirmationToken() != null) {
            jsonHandler.writeAsJson(DtoFactory.createErrorMessage("Invalid user"), response);
        } else if (user.getPassword().equals(password)) {
            final String accessToken = generateAccessToken();

            user.setCurrentAccessToken(accessToken);
            dataLayer.updateObject(user);

            jsonHandler.writeAsJson(DtoFactory.createLoginSuccess(accessToken), response);
        } else {
            jsonHandler.writeAsJson(DtoFactory.createErrorMessage("The email or password you entered is incorrect"), response);
        }
    }

    private String generateAccessToken() {
        return RandomStringUtils.randomAlphanumeric(32);
    }
}
